# 设置 locale 为 UTF-8 以处理中文字符
Sys.setlocale("LC_ALL", "C.UTF-8")
if (Sys.getlocale("LC_ALL") == "") {
  Sys.setlocale("LC_ALL", "en_US.UTF-8")
}

args <- commandArgs(trailingOnly=TRUE)

if (length(args) < 2) {
  stop("需要提供输入文件路径和输出图片路径")
}

input_file <- args[1]
output_img <- args[2]

suppressMessages({
  if (grepl("\\.(xlsx|xls|xlsm)$", input_file, ignore.case = TRUE)) {
    if (!requireNamespace("readxl", quietly = TRUE)) {
      stop("缺少 R 包 readxl，请在 R 中安装：install.packages('readxl')")
    }
    library(readxl)
    data <- readxl::read_excel(input_file)
  } else {
    data <- tryCatch(
      read.csv(input_file, check.names = FALSE, fileEncoding = "UTF-8"),
      error = function(e) {
        # 如果 UTF-8 失败，尝试其他编码
        tryCatch(
          read.csv(input_file, check.names = FALSE, fileEncoding = "GBK"),
          error = function(e2) {
            tryCatch(
              read.csv(input_file, check.names = FALSE, fileEncoding = "GB2312"),
              error = function(e3) stop(paste("读取 CSV 失败，尝试了 UTF-8、GBK、GB2312 编码:", e$message))
            )
          }
        )
      }
    )
  }
})

# 尝试选择第一列的数值列用于绘图
numeric_cols <- which(sapply(data, is.numeric))
if (length(numeric_cols) == 0) {
  # 如果没有数值列，则创建空白图并提示
  png(output_img, width=800, height=600)
  plot.new()
  title(main = "No numeric columns found for histogram")
  dev.off()
} else {
  first_numeric_col <- numeric_cols[1]
  col_name <- names(data)[first_numeric_col]
  
  # 安全处理列名，避免中文字符问题
  safe_col_name <- tryCatch({
    if (Encoding(col_name) == "UTF-8" || Encoding(col_name) == "unknown") {
      col_name
    } else {
      iconv(col_name, from = "UTF-8", to = "UTF-8", sub = "?")
    }
  }, error = function(e) {
    paste("Column", first_numeric_col)
  })
  
  # 获取数值数据并移除NA值
  numeric_data <- data[[first_numeric_col]]
  numeric_data <- numeric_data[!is.na(numeric_data)]
  
  if (length(numeric_data) == 0) {
    png(output_img, width=800, height=600)
    plot.new()
    title(main = paste("No valid numeric data in:", safe_col_name))
    dev.off()
  } else {
    png(output_img, width=800, height=600)
    hist(numeric_data,
         main = paste("Histogram of:", safe_col_name),
         xlab = safe_col_name,
         col = "skyblue", border = "white",
         breaks = "Sturges")  # 使用Sturges方法计算合适的区间数
    dev.off()
  }
}

# 输出所有数据为表格（写入 CSV）
summary_path <- file.path(dirname(output_img), "..", "summary.csv")
summary_path <- normalizePath(summary_path, winslash = "/", mustWork = FALSE)

# 安全写入 CSV，处理编码问题
tryCatch({
  # 尝试使用 UTF-8 编码写入所有数据，确保表头正确
  write.csv(data, summary_path, row.names = FALSE, fileEncoding = "UTF-8", quote = TRUE)
}, error = function(e) {
  tryCatch({
    # 如果 UTF-8 失败，尝试系统默认编码
    write.csv(data, summary_path, row.names = FALSE, quote = TRUE)
  }, error = function(e2) {
    # 最后退回当前工作目录
    write.csv(data, "summary.csv", row.names = FALSE, fileEncoding = "UTF-8", quote = TRUE)
  })
})
